﻿class Main extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            list: [],
            id: 0,
            pagesize: 15,
            start: 1,
            name: '',
            to: '',
            counts: [],
            pagestart: 0,
            orders: 1,
            jumppath:'',
            // cid:1,
        };
    }

    formatlist(list) {
        var listitem = [], wulist = []
        if (list.length > 0) {
            list.forEach((x, i) => {
                listitem.push(
                    <tr key={i}>
                        <td>{x.name}</td>
                        <td className="tdimgbox"><p className="td-img"><img src={`${API_HEAD}imgs/${x.picpath}`} /></p></td>
                        <td onClick={this.setshow.bind(this, x.id, x.state)} className="tconter">{x.state == "1" ? "显示" : "隐藏"}</td>
                        <td onClick={this.toorder.bind(this, x.id)} className="tconter">{x.orders}</td>
                        <td className="operatebox">
                            <div className='operate' id={"ope" + x.id}>
                                <div>
                                    <img src="./src/edit.png" />
                                    <p data-toggle="modal" data-target="#modalOne" className='edit' onClick={this.todetail.bind(this, x.id)}>编辑</p>
                                </div>
                                <div>
                                    <img src="./src/del.png" />
                                    <p className='edit colred' onClick={this.del.bind(this, x.id)}>删除</p>
                                </div>
                            </div>
                        </td>
                    </tr>
                )
            });
        } else {
            wulist.push(
                <p className="wulist">暂无数据</p>
            )
        }
        this.setState({ listitem, list, originallist: list, wulist })
    }
    // 编辑
    todetail(e) {
        var { list, picpath } = this.state, item = [];
        list.forEach(x => {
            if (x.id == e) {
                picpath = `${API_HEAD}imgs/${x.picpath}`
                this.setState({ id: e, picpath, jumppath: x.jumppath, })
            }
        });
        // console.log(item, 'item')
    }
    // 排序
    toorder(id) {
        let orders = prompt("请输入1-999的正整数")
        if (orders == "" || orders == null) {
            return;
        }
        if (isNaN(orders) || orders < 1 || orders > 999) {
            return;
        }
        this.setState({ showloading: 'ON' })
        orders = Math.floor(orders);
        设置类型排序({ id, orders }, res => {
            if (res.issuccess == 1) {
                alert("设置成功");
                // this.flist(res.list);
                this.freshlist();
            } else {
                this.setState({ showloading: '' })
                alert("设置失败");
            }
        });
    }
    // 显示隐藏
    setshow(e, i) {
        this.setState({ showloading: 'ON' })
        修改分类状态(e, res => {
            if (res.issuccess == 1) {
                alert(`${i == "1" ? '隐藏' : '显示'}成功`)
                this.freshlist()
            } else {
                this.setState({ showloading: '' })
                alert(`${i == "1" ? '隐藏' : '显示'}失败`)
            }
        })

    }
    // 删除
    del(e) {
        this.setState({ delid: e }, () => {
            $('#myModal').modal('toggle');
        })
    }
    confirmdel() {
        this.setState({ showloading: 'ON' })
        let { delid, start } = this.state
        swiperdelimg(delid, res => {
            if (res.issuccess == 1) {
                alert('删除成功')
                $('#myModal').modal('toggle');
                this.freshlist()
            } else {
                this.setState({ showloading: '' })
                $('#myModal').modal('toggle');
                alert(res.msg);
            }
        })
    }

    setpager(pagecount, start) {
        let counts = [];
        for (let i = 0; i < pagecount; i++) {
            counts.push(start + i)
        }
        this.setState({ counts, pagestart: 0 })
    }
    clickpage(e) {
        let { start, pagesize } = this.state
        start = (e * pagesize) + 1
        this.setState({ pagestart: e, start }, () => {
            this.freshlist()
        })
    }
    setpage(e) {
        let { pagesize, start } = this.state
        pagesize = parseInt(e)
        start = 1
        this.setState({ pagesize, start }, () => {
            this.freshlist()
        })
    }




    submit() {
        var { picpath,name } = this.state, that = this, err = '', imgarr = [];
       
        if (!picpath) err = "请添加图片"
        if (name=='') err = "请输入名称"
       
        if (err.length > 0) {
            alert(err);
            return;
        }
        this.setState({ showloading: 'ON' }, () => {
            imgarr.push(picpath)
            that.uploadimg(imgarr)
        })

    }

    componentDidMount() {
        let that = this;
        this.setState({ showloading: 'ON', }, () => {
            that.freshlist()

        })

    }

    freshlist() {
        // let { pagesize, start } = this.state;
        typesgetlist(res => {
            this.setState({ showloading: '' })
            if (res.issuccess == 1) {
                // if (start == 1) {
                //     let pagecount = Math.ceil(res.total / pagesize);
                //     this.setpager(pagecount, start);
                //     this.setState({ start, total: res.total })
                // }
                this.formatlist(res.list);
            }
        })

    }

    // 图片
    filechangeimg(e) {
        var that = this;
        var filedata = $('#file' + e)[0].files[0];
        let _name, _fileName, filedatasize = 2048;

        _name = $('#file' + e)[0].value;
        _fileName = _name.substring(_name.lastIndexOf(".") + 1).toLowerCase();
        if (_fileName !== "png" && _fileName !== "jpg" && _fileName !== "gif" && _fileName !== "jpeg") {
            alert("上传图片格式不正确，请重新上传");
        } else {
            if (filedatasize < filedata.size / 1024) {
                alert("上传图片不能大于2M");
                return;
            }

            let filee = e
            var reader = new FileReader();
            reader.readAsDataURL(filedata);
            reader.onload = function (e) {
                var base64str = e.target.result;
                that.putswiperimglistdata([base64str], filee)
            }
        }
    }
    putswiperimglistdata(target, prop) {
        let imgsrc = '', that = this;
        if (prop == 'lb') {
            let lbhtml = [], { lbarr } = that.state
            imgsrc = target[0]
            if (!isBase64(imgsrc)) {
                if (imgsrc.indexOf(`${API_HEAD}`) == -1) {
                    imgsrc = `${API_HEAD}imgs/${imgsrc}`

                }
            }
            lbarr.push(imgsrc)
            lbarr.forEach((x, i) => {
                lbhtml.push(
                    <div className="img_warp">
                        <img src={x} className="img" />
                        <img className='closeimg' onClick={this.del_lbimg.bind(this, i, 'lb')} src='./src/img_close.png' />
                    </div>
                )
            })
            this.setState({ lbhtml, lbarr })
        } else {
            imgsrc = target[0]
            if (!isBase64(imgsrc)) {
                if (imgsrc.indexOf(`${API_HEAD}`) == -1) {
                    imgsrc = `${API_HEAD}imgs/${imgsrc}`

                }
            }
            that.setState({ [prop]: imgsrc })
        }

        // this.setState({
        //     imgsrc, smallimg,// lbimgsrc, lbimgsrcarr
        // })

    }
    clickupload(e) {
        $('#file' + e).click();
    }
    del_img(prop) {
        this.setState({ [prop]: '' })

    }
    // 上传图片
    uploadimg(arr) {
        let uploadimgarr = [],
            {  imgsrc,  name} = this.state, that = this;
        arr.forEach((x, i) => {
            if (x.indexOf(`${API_HEAD}`) == -1) {
                if (isBase64(x)) {
                    uploadimg(x, res => {
                        if (res.issuccess == 1) {
                            x = `${API_HEAD}imgs/${res.path}`
                            uploadimgarr.push(x)
                        } else {
                            alert(res.msg)
                            err = 1
                            return;
                        }
                    })
                }
            } else {
                uploadimgarr.push(x)
            }
        })
        if (uploadimgarr.length == arr.length) {
            uploadimgarr.forEach((x, i) => {
                imgsrc = x.replace(`${API_HEAD}imgs/`, '')
            })

            var data = { picpath:imgsrc, name };
            if (this.state.id > 0) {
                data['id'] = this.state.id;
            }
            console.log(data, 'data');

            typeaoe(data, res => {
                this.setState({ showloading: '' })
                if (res.issuccess == 1) {
                    that.setState({ imgsrc: '', id: 0, jumppath:'', })
                    alert(`${this.state.id > 0 ? '修改' : '保存'}成功`);
                    that.freshlist() 
                } else {
                    alert(res.msg)
                }
            })

        } else {
            this.setState({ showloading: '' })
            alert('图片上传失败')
        }

    }
    inputchange(prop, e) {
        // let { target } = this.state;
        // target[prop] = e.target.value
        // this.setState({ target })
        this.setState({ [prop]: e.target.value })
    }
    add() {
        this.setState({ picpath: '', id: 0, jumppath: '', })
        // $('#modalOne').modal('toggle');
    }

    render() {
        let { listitem, picpath, name } = this.state;

        return (
            <div className="breadLinebox">
                <Loading hidden={this.state.showloading != 'ON'} />
                <Modal content='确定要删除吗？' click={this.confirmdel.bind(this)} />
                <div className="modal fade" id="modalOne" >
                    <div className="modal-dialog">
                        <div className="modal-content">
                            <div className="modal-header border">
                                <p className="modal-title">{this.state.id > 0 ? "编辑" : "新建"}</p>
                                <img data-dismiss="modal" src="./src/close.png" />
                            </div>
                            <div className="input-group">
                                    <span className="input-group-addon">名称</span>
                                    <input id='name' onChange={this.inputchange.bind(this, 'name')} value={name} type="text" placeholder='请输入名称' className="input" />
                                </div>
                            <div className="modal-body">
                                <div className="input-group">
                                    <span className="label input-group-addon">图片</span>
                                    <input onChange={this.filechangeimg.bind(this, 'picpath')} type='file' id='filepicpath' style={{ display: "none" }} />
                                    <div className='detail_btns'>
                                        <img className='fileimg' src='./src/upload_btn.png' onClick={this.clickupload.bind(this, 'picpath')} style={{ display: picpath ? "none" : "" }} />
                                        <div className="img_warp imgsrc" style={{ display: picpath ? "" : "none" }}>
                                            <img src={picpath} className="img" />
                                            <img className='closeimg' onClick={this.del_img.bind(this, 'picpath')} src='./src/img_close.png' />
                                        </div>
                                    </div>
                                </div>
                               
                            </div>
                            <div className="modal-footer border">
                                <button type="button" className="closemod" data-dismiss="modal">关闭</button>
                                <button type="button" onClick={this.submit.bind(this)} data-dismiss="modal" className="submitmod">提交</button>
                            </div>

                        </div>
                    </div>
                </div>
                <div className='content_wrap panel-default content_wrap'>
                    <div className="breadLine">
                        <div className="img">
                            <img src='./src/lm_order1.png' />
                            分类管理
                        </div>
                    </div>
                    <div className="content">
                        {/* <div style={{display:clicknew?"":"none"}} id="div"> */}

                        <div className="tabletit" >
                            {/* <p className="delall"><img src="./src/delall.png"/>批量删除</p> */}
                            <p className="add" data-toggle="modal" data-target="#modalOne" style={{ cursor: 'pointer' }} onClick={this.add.bind(this)}>新建</p>
                        </div>
                        <table className="tab">
                            <thead>
                                <tr>
                                    <th>名称</th>
                                    <th>图片</th>
                                    <th className="tconter">状态<span className="red">（点击切换）</span></th>
                                    <th className="tconter">排序<span className="red">（点击修改）</span></th>
                                    <th className="cz tconter">操作</th>
                                </tr>
                            </thead>
                            <tbody>
                                {listitem}
                            </tbody>
                        </table>
                        {this.state.wulist}

                        {/* <div className="pagerbox">
                            <p>共{this.state.total}条</p>
                            <Pager counts={counts} click={this.clickpage.bind(this)} change={this.setpage.bind(this)} index={pagestart} />
                        </div> */}
                    </div>
                </div>
            </div>


        )


    }
}





ReactDOM.render(
    <div>
        <TopLine />
        <div id='body'>
            <LeftMenu code='types' />
            <Main />
        </div>
    </div>
    // <Barrage/>
    , $('.container')[0]
)